package com.ias.agdis_r.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.ias.agdis_r.R;
import com.ias.agdis_r.application.AGDISApplication;
import com.ias.agdis_r.db.BoxDBHelper;
import com.ias.agdis_r.db.MyBeanTempDBHelper;
import com.ias.agdis_r.db.message.MyMessageBean;
import com.ias.agdis_r.manager.ActionManager;
import com.ias.agdis_r.manager.DataBaseManager;
import com.ias.agdis_r.manager.EffectManager;
import com.ias.agdis_r.manager.JavaBeanManager;
import com.ias.agdis_r.manager.ServiceManage;
import com.ias.agdis_r.manager.ThreadManager;
import com.ias.agdis_r.module.ParameterModel;
import com.ias.agdis_r.netservice.BaseService;
import com.ias.agdis_r.netservice.actions.PrivateNetService;
import com.ias.agdis_r.netservice.actions.PublicNetService;
import com.ias.agdis_r.netservice.actions.WifiNetService;
import com.ias.agdis_r.service.CheckNetService;
import com.ias.agdis_r.util.S;
import com.ias.agdis_r.util.ShowToast;
import com.ias.agdis_r.util.network.NetUtils;
import com.ias.agdis_r.util.sdcard.WriteLog;

import java.io.File;
import java.lang.ref.WeakReference;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

public class StartActivity extends BaseKeyActivity {

    /**
     * 界面最短停留时间
     */
    private static final int MIN_DELAY_TIME = 900;
    /**
     * 程序开始时间
     */
    private long activityStartTime;

    /**
     * 启动MainActivity消息
     */
    private static final int MSG_START_MAIN_ACTIVITY = 0x00000001;
    private static final int SHOW_NODATABASE_TEXTVIEW = 0x00000002;// 显示无配置文件提示
    private static final int GONE_NODATABASE_TEXTVIEW = 0x00000003;// 隐藏无配置文件提示

    private Handler handler = new MyHandler(this);
    private boolean flag_first_time = true;
    private SharedPreferences preferences;
    private static final String KEY_LAST_EDITOR_VAL = "FLIGHT_INPUT_VAL_KEY";
    //private RequestQueue requestQueue;
    private static TextView noDateBase;//没有配置文件提示

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //清空上一次的查询条件
        cleanLastSearch();
        //如果已经跳转到了MainActivity
        if (ParameterModel.startMainActivityFlag) {
            finish();
            return;
        }
        setContentView(R.layout.activity_start);
        noDateBase = (TextView) findViewById(R.id.tv_noDateBase);
        flag_first_time = checkFirstTimeToStart();
        //requestQueue = Volley.newRequestQueue(this);

        activityStartTime = System.currentTimeMillis();
        Settings.System.putInt(StartActivity.this.getContentResolver(), "its_app_running_state", 2);
        if (DataBaseManager.getInstance() == null) {
            new DataBaseManager(getApplicationContext());
        }
        // 读取配置查询航班和今日时间
        JavaBeanManager.getInstance().setHideTodayFlight();
        JavaBeanManager.getInstance().setTodayFlightTime();
        // 配置任务视图模式和查询航班固定资源输入项限制
        JavaBeanManager.getInstance().setGridTaskMode();
        JavaBeanManager.getInstance().setFlightSearchUnlimit();
        getImei();

        // 启动检测SD卡的线程
        new CheckSDTask().execute();
        //清空本地保存的账号信息
        ActionManager.getInstance().getSecurityResponseAction().updateAccountStateProvider(null);
    }

    /**
     * 清空上一次的查询条件
     */
    private void cleanLastSearch(){

        preferences = getPreferences(Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString(KEY_LAST_EDITOR_VAL, "");
        editor.commit();
    }
    private boolean checkFirstTimeToStart() {
        String key = "FLAG_FIRST_TIME_TO_START";
        SharedPreferences preferences =  PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        boolean flag = preferences.getBoolean(key, true);
        if(flag){
            preferences.edit().putBoolean(key, false).apply();
            return true;
        }
        return false;
    }

    /**
     *
     * @return
     */
//    private boolean updateNetConfigFromDns(Response.Listener<JSONObject> callBack, Response.ErrorListener errCallback) {
//        final String url = DataBaseManager.getInstance().getString(ParameterModel.T_DNS_CONFIG, "url");
//        if(S.isNotEmpty(url)){
//            Log.i("C_net_config", "get net config from " + url);
//            JsonObjectRequest request = new JsonObjectRequest(url,callBack,errCallback);
//            requestQueue.add(request);
//        }else{
//            Log.w("C_net_config","Can not find url config from " + ParameterModel.T_DNS_CONFIG  + ", which was used to query net config from dns server.");
//            return false;
//        }
//
//        return  true;
//    }

    /**
     * 启动MainActivity,界面停留时间必须大于等于MIN_DELAY_TIME
     */
    private void gotoMainActivity() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent intent = null;
                //异常退出，直接到登录界面
                SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
                if (preferences.getBoolean(AGDISApplication.PREF_UNCAUGHT_EXCEPTION_HAPPENED, false)) {
                    intent = new Intent(StartActivity.this, LoginActivity.class);
                    intent.putExtra(LoginActivity.EXTRA_EXCEPTION_EXIST_RELOGIN, true);
                    ShowToast.get().show(getString(R.string.autoLogin));
                    SharedPreferences.Editor editor = preferences.edit();
                    editor.putBoolean(AGDISApplication.PREF_UNCAUGHT_EXCEPTION_HAPPENED, false);
                    editor.apply();
                } else {
                    intent = new Intent(StartActivity.this, MainActivity.class);
                }
                startActivity(intent);
                finish();

            }
        }, activityStartTime + MIN_DELAY_TIME - System.currentTimeMillis());

    }

    /**
     * 更新IMEI号
     */
    public void getImei() {
        TelephonyManager tM = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        ParameterModel.IMEI_ID = S.valueOf(tM.getDeviceId()).trim();
        if (S.isEmpty(ParameterModel.IMEI_ID)) {
            WriteLog.getInstance().writeLog("imei为空,启动获取imei线程");
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (S.isEmpty(ParameterModel.IMEI_ID)) {
                        try {
                            Thread.sleep(500);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        TelephonyManager tM = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
                        ParameterModel.IMEI_ID = tM.getDeviceId();
                        WriteLog.getInstance().writeLog("ParameterModel.IMEI_ID:" + ParameterModel.IMEI_ID);
                    }
                }
            }).start();
        } else {
            Log.i("imei", "imei：" + ParameterModel.IMEI_ID);
            WriteLog.getInstance().writeLog("imei：" + ParameterModel.IMEI_ID);
            System.out.println("imei：" + ParameterModel.IMEI_ID);
        }
    }

    private static final long DELAY_TIME = 1000 * 2;// 设置DELAY_TIME秒后自动跳转
    private static final long CHECKSD_TIME = 1000 * 1; // 检测SD卡间隔时间
    public static final int ACTION_KEY_JIANPAN_UP = 201;
    public static final int ACTION_SHOW_DIALOG_DOWNLOAD = 301;
    private String[] strs;// 网路顺序
    private HeaderHandler headerHandler = new HeaderHandler(Looper.myLooper());

    class CheckSDTask extends AsyncTask<Void, Void, Void> {
        private Drawable back_drawable = null;

        @Override
        protected Void doInBackground(Void... arg0) {

            while (true) {
//                back_drawable = DataBaseManager.getInstance().getImage("hit12_background.png");
//                Log.i("tag", "back_drawable:" + back_drawable);
                int code = DataBaseManager.getInstance().isDataBaseExist();
                if (code == 1 && S.isNotEmpty(ParameterModel.IMEI_ID)) {
                    Message msg = new Message();
                    msg.what = GONE_NODATABASE_TEXTVIEW;
                    handler.sendMessage(msg);
                    //DNS 加载服务器地址代码
//                    Response.Listener<JSONObject> callback =  new Response.Listener<JSONObject>() {
//                        @Override
//                        public void onResponse(JSONObject response) {
//                            Log.i("C_net_config", "get net config(" + response + ") success.");
//                            new DnsIpConfigHelper(DataBaseManager.getInstance()).saveConfig(response);
//                            if(null != requestQueue)
//                            requestQueue.stop();
//                            publishProgress();
//                        }
//                    };
//
//                    Response.ErrorListener errorListener =  new Response.ErrorListener() {
//                        @Override
//                        public void onErrorResponse(VolleyError error) {
//                            Log.w("C_net_config","Load config error:" + error.toString());
//                            publishProgress();
//                        }
//                    };
//
//                    //第一次启动，到DNS加载网络配置
//                    if(flag_first_time){
//                        boolean flg = updateNetConfigFromDns(callback,errorListener);
//                        if(!flg){
//                            publishProgress();
//                        }
//
//                    }else{
                        publishProgress();
//                    }

                    break;
                }else if (code == -1 || S.isEmpty(ParameterModel.IMEI_ID)){
                    Message msg = new Message();
                    msg.what = SHOW_NODATABASE_TEXTVIEW;
                    handler.sendMessage(msg);
                }
                try {
                    Thread.sleep(CHECKSD_TIME);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            return null;

        }

        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
        }

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
        }

        @Override
        protected void onProgressUpdate(Void... arg0) {
            // TODO Auto-generated method stub

            // initEqualizer(); //均衡器初始化
            // 继续加载
            // child.setBackGround(back_drawable);
            // startMainPage();
            new Thread() {
                public void run() {
                    try {
                        Thread.sleep(DELAY_TIME);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    headerHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            EffectManager.getInstance().initVoice();
                            startNetService();
                            boolean usinggps = DataBaseManager.getInstance().getBoolean(ParameterModel.T_GPS_INFO,
                                    ParameterModel.ISUSING);
                            ParameterModel.isBoxPopMode = DataBaseManager.getInstance().getBoolean(ParameterModel.T_BOX_SETTING,
                                    ParameterModel.BOX_POP);
                            if (usinggps) {
                            }
                            initSDData();
                            // 启动路由服务程序
                            startRouteService();
                            //启动小球工具
                            startFloattool();
                            // 启动完成，跳转到MainActivity
                            gotoMainActivity();
                        }
                    });
                }
            }.start();
        }

    }

    /**
     * 查询数据库启动选择的服务
     */
    public void startNetService() {
        // ---------------------------------测试
        ServiceManage s = ServiceManage.getInstance();
        String netList = DataBaseManager.getInstance().getString(ParameterModel.T_NET_SELECT_INFO,
                ParameterModel.NET_LIST);
        WriteLog.getInstance().writeDebugLog(getString(R.string.DEBUG_NET_SELECTED)+netList);
        System.out.println(getString(R.string.DEBUG_NET_SELECTED) + netList);
        strs = netList.split(",");
        for (String str : strs) {
            BaseService service = null;
            if (ParameterModel.PUBLIC_TAB_NUM.equals(str)) {
                service = new PublicNetService(headerHandler, StartActivity.this);
            } else if (ParameterModel.PRIVATE_TAB_NUM.equals(str)) {
                service = new PrivateNetService(headerHandler, StartActivity.this);
            } else if (ParameterModel.WIFI_TAB_NUM.equals(str)) {
                service = new WifiNetService(headerHandler, StartActivity.this);
            }
            if (service != null)
                s.addService(service);
        }
        // 启动 检测SOCKET线程
        ThreadManager.getInstance().startConnectSocketThread();
    }

    private void initSDData() {
        // TODO Auto-generated method stub
        String data = DataBaseManager.getInstance().getString(ParameterModel.T_DONTDELETEME,
                ParameterModel.T_DONTDELETEME);
        if (S.isEmpty(data)) {
            DataBaseManager.getInstance().insert(ParameterModel.T_DONTDELETEME, ParameterModel.T_DONTDELETEME, "#ias@");
        }
        NetUtils.PHONE_STATUS = DataBaseManager.getInstance().getString(ParameterModel.T_DONTDELETEME,
                ParameterModel.PHONE_STATUS);

        String logCheck = DataBaseManager.getInstance().getString( // 是否开启日志
                // add
                // by
                // zhangsc
                ParameterModel.T_LOG, ParameterModel.LOG_CHECK);
        String logSize = DataBaseManager.getInstance().getString( // 日志设置大小
                // add
                // by
                // zhangsc
                ParameterModel.T_LOG, ParameterModel.LOG_SIZE);

        if (S.isEmpty(logCheck) || S.isEmpty(logSize)) {// add by zhangsc
            // 增加日志配置文件
            DataBaseManager.getInstance().insert(ParameterModel.T_LOG, ParameterModel.LOG_CHECK, "1");
            DataBaseManager.getInstance().insert(ParameterModel.T_LOG, ParameterModel.LOG_SIZE, "10");
        }
        deleteBox();
        delPhoto();
    }

    /**
     * 启动路由服务
     */
    private void startRouteService() {

        //读取本地存储的AGDIS更新URL
        String pubUrl = DataBaseManager.getInstance().getString(ParameterModel.UPDATE_CONFIG_PACKAGE, ParameterModel.T_UPDATE_CONFIG,
                ParameterModel.AGDIS_PUB_UP_URL);
        String priUrl = DataBaseManager.getInstance().getString(ParameterModel.UPDATE_CONFIG_PACKAGE, ParameterModel.T_UPDATE_CONFIG,
                ParameterModel.AGDIS_PRI_UP_URL);
        //如果没有内容，写入string.xml中的配置
        if (S.isEmpty(pubUrl)) {
            pubUrl = DataBaseManager.getInstance().getContext().getResources().getString(R.string.pubupdateurl);
            //写入配置
            DataBaseManager.getInstance().insert(ParameterModel.UPDATE_CONFIG_PACKAGE, ParameterModel.T_UPDATE_CONFIG, ParameterModel.AGDIS_PUB_UP_URL, pubUrl);
        }
        //如果没有内容，写入string.xml中的配置
        if (S.isEmpty(priUrl)) {
            priUrl = DataBaseManager.getInstance().getContext().getResources().getString(R.string.priupdateurl);
            //写入配置
            DataBaseManager.getInstance().insert(ParameterModel.UPDATE_CONFIG_PACKAGE, ParameterModel.T_UPDATE_CONFIG, ParameterModel.AGDIS_PRI_UP_URL, priUrl);
        }

        if (S.checkAppInstall("com.routeservice")) {
            Intent intent = new Intent("ias.routeservice");
            Bundle bundle = new Bundle();
            String netList = DataBaseManager.getInstance().getString(ParameterModel.T_NET_SELECT_INFO,
                    ParameterModel.NET_LIST);
            strs = netList.split(",");
            String sRouteList = null;
            for (String str : strs) {
                String route = null;
                if (ParameterModel.PRIVATE_TAB_NUM.equals(str)) {// 专网

                    // TODO 添加专网路由
                    String str_push_destination = DataBaseManager.getInstance().getString(ParameterModel.T_PRIVATE_INFO,
                            ParameterModel.NET_IP_PUSH);
                    String str_restful_destination = DataBaseManager.getInstance()
                            .getString(ParameterModel.T_PRIVATE_INFO, ParameterModel.NET_IP_RESTFUL);
                    String str_genmask = "255.255.255.255";

                    String route_push = "destination" + str_push_destination + ",genmask" + str_genmask + ",dev"
                            + ParameterModel.PRIVATE_TAB_NUM;
                    String rout_restful = "destination" + str_restful_destination + ",genmask" + str_genmask + ",dev"
                            + ParameterModel.PRIVATE_TAB_NUM;

                    System.out.println("专网路由：" + route);

                    sRouteList = route_push + ParameterModel.VALUE_REGULAREXPRESSION + rout_restful;

                    if (S.isNotEmpty(priUrl)) {
                        if (priUrl.indexOf("//") > -1) {
                            priUrl = priUrl.substring(priUrl.indexOf("//") + 2, priUrl.length() - 1);
                            //获取URL的IP地址
                            String updateIp = "";
                            if (priUrl.indexOf(":") > -1) {
                                updateIp = priUrl.substring(0, priUrl.indexOf(":"));
                            } else if (priUrl.indexOf("/") > -1) {
                                updateIp = priUrl.substring(0, priUrl.indexOf("/"));
                            }

                            //如果获取更新的地址合法，且该地址不在路由信息列表中
                            if (S.isIP(updateIp) && sRouteList.indexOf(updateIp) == -1) {
                                //添加路由
                                route = "destination" + updateIp + ",genmask" + str_genmask + ",dev" + ParameterModel.PRIVATE_TAB_NUM;
                                Log.i("AGDIS", "需要添加更新应用路由:" + route);
								WriteLog.getInstance().writeLog(getString(R.string.newRouting) + route);
                                System.out.println(getString(R.string.newRouting) + route);
                                sRouteList = sRouteList + ParameterModel.VALUE_REGULAREXPRESSION + route;
                            }
                        }
                    }
                }
            }
            String[] routelist = null;
            if (sRouteList != null) {
                routelist = sRouteList.split(ParameterModel.VALUE_REGULAREXPRESSION);
            }

            String private_net_tab = DataBaseManager.getInstance().getString(ParameterModel.T_PRIVATE_INFO,
                    ParameterModel.PRIVATE_NET_TAB);
            // 专网切回最小信号强度
            int private_up_rssi = DataBaseManager.getInstance().getInt(ParameterModel.T_PRIVATE_INFO,
                    ParameterModel.PRIVATE_UP_RSSI);
            // 专网切出最小信号强度
            int private_down_rssi = DataBaseManager.getInstance().getInt(ParameterModel.T_PRIVATE_INFO,
                    ParameterModel.PRIVATE_DOWN_RSSI);
            // 专网切回最小信号质量
            int private_up_cinr = DataBaseManager.getInstance().getInt(ParameterModel.T_PRIVATE_INFO,
                    ParameterModel.PRIVATE_UP_CINR);
            // 专网切出最小信号质量
            int private_down_cinr = DataBaseManager.getInstance().getInt(ParameterModel.T_PRIVATE_INFO,
                    ParameterModel.PRIVATE_DOWN_CINR);

            // 是否执行PING动作
            int switch_ping = DataBaseManager.getInstance().getInt(ParameterModel.T_NET_SELECT_INFO,
                    ParameterModel.SWITCH_PING);

            boolean logRoute = DataBaseManager.getInstance().getBoolean(ParameterModel.T_PRIVATE_INFO,
                    ParameterModel.LOG_ROUTE);

            // 获取专网因信号跳变而切网的确认次数
            int down_max, up_max;
            down_max = DataBaseManager.getInstance().getInt(ParameterModel.T_PRIVATE_INFO,
                    ParameterModel.PRIVATE_DOWN_MAX);
            up_max = DataBaseManager.getInstance().getInt(ParameterModel.T_PRIVATE_INFO, ParameterModel.PRIVATE_UP_MAX);

            if (private_up_rssi != 0) {
                bundle.putInt("PRIVATE_UP_RSSI", private_up_rssi);
            }
            if (private_down_rssi != 0) {
                bundle.putInt("PRIVATE_DOWN_RSSI", private_down_rssi);
            }

            if (private_up_cinr != 0) {
                bundle.putInt("PRIVATE_UP_CINR", private_up_cinr);
            }
            if (private_down_cinr != 0) {
                bundle.putInt("PRIVATE_DOWN_CINR", private_down_cinr);
            }

            if (down_max != 0) {
                bundle.putInt("PRIVATE_DOWN_MAX", down_max);
            }
            if (up_max != 0) {
                bundle.putInt("PRIVATE_UP_MAX", up_max);
            }

            bundle.putString("PRIVATE_NET_TAB", private_net_tab);
            bundle.putInt("SWITCH_PING", switch_ping);
            bundle.putStringArray("routelist", routelist);
            bundle.putBoolean("LOG_CHECK", logRoute); // 路由程序日志开关
            bundle.putString("CHECK_NET", netList);
            intent.putExtras(bundle);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            WriteLog.getInstance().writeLog(getString(R.string.START_ROUTESERVICE));
            startService(intent);
        } else {
            WriteLog.getInstance().writeLog(getString(R.string.START_AGDIS_NETSERVICE));
            Intent service = new Intent(StartActivity.this, CheckNetService.class);
            this.startService(service);
        }
    }

    public void startFloattool() {

        try {
            Intent intent = new Intent("ias.floattool");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            //启动小球工具
            startService(intent);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    static class MyHandler extends Handler {
        WeakReference<StartActivity> mActivity;

        public MyHandler(StartActivity activity) {
            this.mActivity = new WeakReference<StartActivity>(activity);
        }

        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case MSG_START_MAIN_ACTIVITY:
                    mActivity.get().gotoMainActivity();
                    break;
                case SHOW_NODATABASE_TEXTVIEW:
                    noDateBase.setVisibility(View.VISIBLE);
                    break;
                case GONE_NODATABASE_TEXTVIEW:
                    noDateBase.setVisibility(View.GONE);
                    break;
            }
        }
    }

    private void deleteBox() {
        SimpleDateFormat matter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        final Calendar c = Calendar.getInstance();
        int mCurrentDay = c.get(Calendar.DAY_OF_MONTH);
        c.set(Calendar.DAY_OF_MONTH, mCurrentDay - 3);
        String[] date3 = new String[]{matter.format(c.getTime())};
        MyBeanTempDBHelper<MyMessageBean> messageDBHelper = new MyBeanTempDBHelper<MyMessageBean>(
                getApplicationContext(), MyMessageBean.class);
        messageDBHelper.creatTable();
        messageDBHelper.close();
        BoxDBHelper dbHelper = new BoxDBHelper(getApplicationContext());
        dbHelper.deleteDate3(BoxDBHelper.TABLE_TASK, "time", date3);
        dbHelper.deleteDate3(BoxDBHelper.TABLE_FLIGHT, "time", date3);
        dbHelper.deleteDate3(BoxDBHelper.TABLE_MESSAGE, "stm", date3);
        // 任务进展暂时无用，删除3天前的数据
        dbHelper.deleteDate3(BoxDBHelper.TABLE_TASKPROCESS, "time", date3);
        dbHelper.deleteDate3(BoxDBHelper.TABLE_LUGGAGEBARCODE, "scanTime", date3);
        dbHelper.deleteDate3(BoxDBHelper.TABLE_TASKCHOOSEMEMBER, "time", date3);
        dbHelper.closeDB();
    }

    private void delPhoto(){

        try {
            File file =  new File(DataBaseManager.PHOTO_FORDER_PATH);
            File[] filses = file.listFiles();
            String sNowTime = S.getNowTime();
            ArrayList<File> delList = new ArrayList<File>();
            for(File subfile:filses){
                SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMddHHmmss");
                String photoName = subfile.getName();
                int index = photoName.indexOf("_");
                String sphotoTime = "";
                if(index!=-1){
                    sphotoTime = photoName.substring(0,index);
                }else{
                    sphotoTime = photoName.substring(0,photoName.length()-4);
                }
                Date dateNowTime = simpleDateFormat.parse(sNowTime);
                Date datePhotoTime = simpleDateFormat.parse(sphotoTime);

                Calendar cNowTime = Calendar.getInstance();
                cNowTime.setTime(dateNowTime);
                int dayNowTimeIndex = cNowTime.get(Calendar.DAY_OF_YEAR);
                int hourNowTimeIndex = cNowTime.get(Calendar.HOUR_OF_DAY);

                Calendar cPhotoTime = Calendar.getInstance();
                cPhotoTime.setTime(datePhotoTime);
                int dayPhotoTimeIndex = cPhotoTime.get(Calendar.DAY_OF_YEAR);
                int hourPhotoTimeIndex = cPhotoTime.get(Calendar.HOUR_OF_DAY);

                if(dayNowTimeIndex-dayPhotoTimeIndex>7){//如果相隔时间大于7天
                    delList.add(subfile);

                }else if(dayNowTimeIndex-dayPhotoTimeIndex==7&&hourNowTimeIndex>hourPhotoTimeIndex){//如果相隔时间等于7天，且当前小时大于图片小时
                    delList.add(subfile);
                }
            }
            for(File delFile:delList){
                boolean  flag = delFile.delete();
                WriteLog.getInstance().writeLog("删除过期照片："+delFile.getName()+"|"+flag);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class HeaderHandler extends Handler {
    public HeaderHandler(Looper looper) {
        super(looper);
    }
}
